<?php
/**
 * Created by PhpStorm.
 * Author: sitenv@aliyun.com
 * CreateTime: 2021/07/16 13:53
 * Blog：www.myblogs.xyz
 */

namespace app\admin\controller;


use app\common\service\CommonService;
use think\facade\View;

class Messages extends Common
{
    public function index()
    {
        $param = input('param.');
        $list_where = [];
        // 查询时间
        $start_time = empty($param['start_time']) ? '' : str_replace('%2B', ' ', $param['start_time']);
        $end_time = empty($param['end_time']) ? '' : str_replace('%2B', ' ', $param['end_time']);
        if (!empty($start_time)){
            if (strtotime($start_time)){
                $beg = strtotime($start_time);
                if (!empty($end_time) && strtotime($end_time)){
                    $end = strtotime($end_time);
                }else{
                    $date = date('Y-m-d',NEW_TIME) . ' 23:59:59';
                    $end = strtotime($date);
                }
                $list_where['create_time'] = [['egt',$beg],['elt',$end]];
            }
        }
        $messages_model = new \app\common\model\Messages();
        $data = $messages_model->messagesLists($list_where, 10, 'create_time desc,messages_id desc');

        View::assign([
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'count'=>$data['count'],
            'list'=>$data['list'],
            'page'=>$data['page']
        ]);
        return View::fetch();
    }

    public function insertMessages()
    {
        $this->saveMessages();
        return View::fetch('save_messages');
    }

    public function updateMessages()
    {
        $this->saveMessages();
        return View::fetch('save_messages');
    }

    protected function saveMessages()
    {
        $messages_id = input('param.messages_id', 0, 'intval');
        $messages_model = new \app\common\model\Messages();
        if (request()->isPost())
        {
            $data = input('post.');
            $new_time = NEW_TIME;
            if (empty($data[$messages_model->getPk()])){
                $data['create_time'] = $new_time;
                $data['update_time'] = $new_time;
                if (!$messages_model->operation($data)){
                    $message = $messages_model->getError() == false ? '保存失败' : $messages_model->getError();
                    $this->returnError($message);
                }
            }else{
                $data['update_time'] = $new_time;
                if (!$messages_model->operation($data)){
                    $message = $messages_model->getError() == false ? '保存失败' : $messages_model->getError();
                    $this->returnError($message);
                }
            }
            $this->returnSuccess('保存成功');
        }
        $oldData = $messages_model->getFind($messages_id);
        if (!empty($oldData)){
            $oldData['target_name'] = '全部';
            if (!empty($oldData['target_id'])){
                if ($oldData['target'] == 1){
                    $member_model = new \app\common\model\Member();
                    $oldData['target_name'] = $member_model->getField($oldData['target_id'], 'mobile');
                }
                if ($oldData['target'] == 2){
                    $admin_model = new \app\common\model\Admin();
                    $oldData['target_name'] = $admin_model->getField($oldData['target_id'], 'nickname');
                }
            }
            $oldData['create_time'] = date('Y-m-d H:i:s', $oldData['create_time']);
        }

        View::assign('oldData', $oldData);
    }

    public function sendMessages()
    {
        $messages_id = input('param.messages_id', 0, 'intval');
        if (empty($messages_id)){
            $this->returnError('操作失败');
        }
        $data = [
            'is_send' => 1,
            'send_time' => NEW_TIME,
            'messages_id' => $messages_id,
        ];
        $messages_model = new \app\common\model\Messages();
        $message_data = $messages_model->getFind($messages_id);
        $rows = $messages_model->update($data);
        if (empty($rows)){
            $this->returnError('发送失败');
        }
        if ($message_data['is_push'] == 1){
            $is_push = true;
            if (!empty($message_data['target_id'])){
                $token = $this->getAlias(['target'=>$message_data['target'],'target_id'=>$message_data['target_id']], true);
                if (empty($token)){
                    $is_push = false;
                }
            }else{
                $token = '';
            }
            if ($is_push){
                $title = $message_data['contents'];
                $extras = [
                    'type'=>'system',
                    'contents'=>$message_data['contents'],
                    'ids'=>$messages_id
                ];
                $setting_model = new \app\common\model\Setting();
                $setting_model->ruleExec($title, $token, $extras);
            }
        }
        $this->returnSuccess('发送成功');
    }

    public function deleteMessages()
    {
        if (CommonService::delete()){
            $this->returnSuccess('删除成功');
        }
        $this->returnError('删除失败');
    }

    public function getAlias($data, $is_token = false)
    {
        $alias = [];
        $member_model = new \app\common\model\Member();
        $admin_model = new \app\common\model\Admin();
        // 是否是全部推送
        // target 接收端：0全部，1用户，2代理商
        // target_id 是否指定推送目标
        if (empty($data['target_id'])){
            if ($data['target'] == 1){
                if ($is_token){
                    $member_model->fields = 'token';
                }else{
                    $member_model->fields = 'member_id';
                }
                $member_list = $member_model->getList();
                if (!empty($member_list)){
                    $account = array_removal($member_list);
                    if (is_array($account)){
                        foreach ($account as $key=>$val){
                            $alias[] = $val . '';
                        }
                    }
                }
            }
            if ($data['target'] == 2){
                if ($is_token){
                    $admin_model->fields = 'account';
                }else{
                    $admin_model->fields = 'admin_id';
                }
                $admin_list = $admin_model->getList();
                if (!empty($admin_list)){
                    $account = array_removal($admin_list);
                    if (is_array($account)){
                        foreach ($account as $key=>$val){
                            $alias[] = $val . '';
                        }
                    }
                }
            }
        }else{
            if ($data['target'] == 1){
                if ($is_token){
                    $member_model->fields = 'token';
                }else{
                    $member_model->fields = 'member_id';
                }
                $token = $member_model->getField($data['target_id']);
                if (!empty($token)){
                    $alias[] = $token . '';
                }
            }
            if ($data['target'] == 2){
                if ($is_token){
                    $admin_model->fields = 'account';
                }else{
                    $admin_model->fields = 'admin_id';
                }
                $account = $admin_model->getField($data['target_id']);
                if (!empty($account)){
                    $alias[] = $account . '';
                }
            }
        }
        if (empty($alias)){
            $this->returnError('获取接收账户信息失败');
        }
        return $alias;
    }

}